<template>
  <div class="feedback-management-container">
    <!-- 统一标题样式 -->
    <div class="header-section">
      <h2>反馈管理</h2>
      <div class="title-line"></div>
    </div>

    <!-- 搜索与筛选区域 -->
    <el-card class="filter-card">
      <div class="filter-content">
        <div class="filter-row">
          <el-select v-model="searchForm.status" placeholder="全部状态" clearable @change="loadFeedbackData" style="width: 140px;">
            <el-option label="待处理" value="pending" />
            <el-option label="处理中" value="processing" />
            <el-option label="已解决" value="resolved" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>

          <el-select v-model="searchForm.feedbackType" placeholder="全部类型" clearable @change="loadFeedbackData" style="width: 140px;">
            <el-option label="问题" value="question" />
            <el-option label="系统" value="system" />
            <el-option label="建议" value="suggestion" />
            <el-option label="其他" value="other" />
          </el-select>

          <el-select v-model="searchForm.timeRange" placeholder="全部时间" clearable @change="loadFeedbackData" style="width: 140px;">
            <el-option label="今天" value="today" />
            <el-option label="近3天" value="3days" />
            <el-option label="近1周" value="week" />
            <el-option label="1周前" value="overweek" />
          </el-select>

          <el-select v-model="searchForm.searchType" placeholder="搜索类型" clearable style="width: 120px;">
            <el-option label="内容" value="content" />
            <el-option label="用户ID" value="userId" />
          </el-select>
        </div>

        <div class="search-actions">
          <el-input 
            v-model="searchForm.keyword" 
            placeholder="请输入关键词" 
            clearable
            @clear="loadFeedbackData"
            style="width: 300px">
            <template #prepend>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <div class="filter-actions">
            <el-button 
              class="custom-primary-button"
              type="primary" 
              @click="loadFeedbackData">
              搜索反馈
            </el-button>
            <el-button 
              class="custom-reset-button"
              @click="resetFilters">
              重置筛选
            </el-button>
            <el-button 
              class="custom-refresh-button"
              @click="refreshFeedback">
              <el-icon><Refresh /></el-icon> 刷新
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 反馈列表卡片 -->
    <el-card class="feedback-list-card">
      <div class="list-header">
        <div class="header-gradient"></div>
        <h3>反馈列表</h3>
        <div class="total-feedbacks">
          共 <span class="highlight">{{ pagination.total || 0 }}</span> 条反馈
        </div>
      </div>

      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
        class="feedback-table"
      >
        <el-table-column prop="username" label="用户" width="120">
          <template #default="{row}">
            <div class="user-info">
              <el-avatar :size="32" :src="getDefaultAvatar()" />
              <span class="username">{{ row.username || '未知用户' }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="title" label="标题" min-width="200">
          <template #default="{row}">
            <div class="title-cell">
              <span class="title-text">{{ row.title }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="feedbackType" label="类型" width="100">
          <template #default="{row}">
            <el-tag :type="getTypeTag(row.feedbackType)" effect="dark" round>
              {{ formatType(row.feedbackType) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{row}">
            <el-tag :type="getStatusTag(row.status)" effect="dark" round>
              {{ formatStatus(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="提交时间" width="180">
          <template #default="{row}">
            <div class="time-cell">
              <el-icon><Calendar /></el-icon>
              <span>{{ formatDate(row.createdAt) }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="180">
          <template #default="{row}">
            <div class="action-buttons">
              <el-button 
                class="detail-button"
                link 
                type="primary" 
                size="small" 
                @click="showDetail(row)">
                <el-icon><View /></el-icon> 查看
              </el-button>
              <el-button
                class="delete-button"
                link
                type="danger"
                size="small"
                @click="handleDelete(row.feedbackId)">
                <el-icon><Delete /></el-icon> 删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total || 0"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 反馈详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="反馈详情"
      width="600px"
      class="feedback-detail-dialog"
    >
      <div v-if="currentFeedback" class="feedback-detail-card">
        <div class="feedback-header">
          <div class="feedback-user">
            <el-avatar :size="60" :src="getDefaultAvatar()" />
            <div class="user-details">
              <div class="user-name">{{ currentFeedback.username }}</div>
              <div class="feedback-meta">
                <el-tag :type="getTypeTag(currentFeedback.feedbackType)" effect="dark" size="small">
                  {{ formatType(currentFeedback.feedbackType) }}
                </el-tag>
                <el-tag :type="getStatusTag(currentFeedback.status)" effect="dark" size="small">
                  {{ formatStatus(currentFeedback.status) }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>

        <el-divider />

        <div class="detail-grid">
          <div class="detail-item full-width">
            <span class="detail-label">反馈标题：</span>
            <span class="detail-value">{{ currentFeedback.title }}</span>
          </div>
          
          <div class="detail-item full-width">
            <span class="detail-label">反馈内容：</span>
            <div class="content-box">{{ currentFeedback.content }}</div>
          </div>
          
          <div class="detail-item">
            <span class="detail-label">提交时间：</span>
            <span class="detail-value">{{ formatDateTime(currentFeedback.createdAt) }}</span>
          </div>
          
          <div class="detail-item full-width">
            <span class="detail-label">管理员回复：</span>
            <div class="reply-box">{{ currentFeedback.adminReply || '暂无回复' }}</div>
          </div>
        </div>
      </div>
      <div v-else>
        <el-empty description="加载中..." />
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, View, Delete, Calendar } from '@element-plus/icons-vue'
import {
  getFeedbackList,
  deleteFeedback,
  refreshFeedbackList
} from '@/api/feedback'

// 数据定义
const tableData = ref([])
const currentFeedback = ref(null)
const detailVisible = ref(false)
const loading = ref(false)

// 分页数据
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 搜索表单
const searchForm = ref({
  status: '',
  feedbackType: '',
  timeRange: '',
  searchType: 'content',
  keyword: ''
})

// 获取默认头像
const getDefaultAvatar = () => {
  return "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
}

// 加载反馈数据
const loadFeedbackData = async () => {
  try {
    loading.value = true
    const params = {
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
      status: searchForm.value.status,
      feedbackType: searchForm.value.feedbackType,
      timeRange: searchForm.value.timeRange,
      searchType: searchForm.value.searchType,
      keyword: searchForm.value.keyword
    }
    const res = await getFeedbackList(params)
    tableData.value = (res.list || []).map(item => ({
      ...item,
      username: item.username || '未知用户'
    }))
    pagination.value.total = res.total || 0
  } catch (error) {
    ElMessage.error('加载反馈列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 重置筛选
const resetFilters = () => {
  searchForm.value = {
    status: '',
    feedbackType: '',
    timeRange: '',
    searchType: 'content',
    keyword: ''
  }
  pagination.value.pageNum = 1
  loadFeedbackData()
}

// 刷新反馈列表
const refreshFeedback = async () => {
  try {
    loading.value = true
    const res = await refreshFeedbackList()
    tableData.value = (res || []).map(item => ({
      ...item,
      username: item.username || '未知用户'
    }))
    pagination.value.pageNum = 1
    ElMessage.success('刷新成功')
  } catch (error) {
    ElMessage.error('刷新失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 查看详情
const showDetail = (row) => {
  currentFeedback.value = {
    username: row.username || '未知用户',
    feedbackType: row.feedbackType,
    status: row.status,
    title: row.title,
    content: row.content,
    createdAt: row.createdAt,
    adminReply: row.adminReply
  }
  detailVisible.value = true
}

// 删除反馈
const handleDelete = (id) => {
  ElMessageBox.confirm('确定删除这条反馈吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteFeedback(id)
      ElMessage.success('删除成功')
      loadFeedbackData()
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    }
  }).catch(() => {})
}

// 分页变化
const handlePageChange = (page) => {
  pagination.value.pageNum = page
  loadFeedbackData()
}

const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  pagination.value.pageNum = 1
  loadFeedbackData()
}

// 格式化方法
const formatType = (type) => {
  const map = {
    'question': '问题',
    'system': '系统',
    'suggestion': '建议',
    'other': '其他'
  }
  return map[type] || type
}

const formatStatus = (status) => {
  const map = {
    'pending': '待处理',
    'processing': '处理中',
    'resolved': '已解决',
    'rejected': '已拒绝'
  }
  return map[status] || status
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  try {
    const date = new Date(dateStr)
    return date.toLocaleString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (e) {
    return dateStr
  }
}

const formatDateTime = (dateStr) => {
  if (!dateStr) return '未知时间'
  try {
    const date = new Date(dateStr)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    }).replace(/\//g, '-')
  } catch (e) {
    return dateStr
  }
}

// 标签样式
const getTypeTag = (type) => {
  const map = {
    'question': 'primary',
    'system': 'danger',
    'suggestion': 'success',
    'other': 'info'
  }
  return map[type] || ''
}

const getStatusTag = (status) => {
  const map = {
    'pending': 'warning',
    'processing': '',
    'resolved': 'success',
    'rejected': 'danger'
  }
  return map[status] || ''
}

// 初始化加载
onMounted(() => {
  loadFeedbackData()
})
</script>

<style scoped>
/* 整体布局和背景 */
.feedback-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 标题区域 */
.header-section {
  margin-bottom: 5px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e6e9ed;
}

.header-section h2 {
  color: #1a2f54;
  font-weight: 600;
  font-size: 22px;
  margin-bottom: 8px;
}

.title-line {
  width: 50px;
  height: 4px;
  background: linear-gradient(90deg, #3b527a, #4e6694);
  border-radius: 2px;
}

/* 卡片通用样式 */
.filter-card, .feedback-list-card {
  border-radius: 10px;
  margin-bottom: 24px;
  border: none;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

/* 筛选区域样式 */
.filter-content {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.filter-row {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
  align-items: center;
}

.search-actions {
  display: flex;
  align-items: center;
  gap: 15px;
  justify-content: space-between;
}

.filter-actions {
  display: flex;
  gap: 10px;
}

/* 按钮样式 */
.custom-primary-button {
  background: linear-gradient(135deg, #4e6694 0%, #3b527a 100%);
  border: none;
  color: white;
  transition: all 0.3s;
  box-shadow: 0 2px 6px rgba(26, 47, 84, 0.3);
}

.custom-primary-button:hover {
  background: linear-gradient(135deg, #3b527a 0%, #4e6694 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(26, 47, 84, 0.4);
}

.custom-reset-button {
  background: #f0f2f5;
  border-color: #dcdfe6;
  color: #606266;
  transition: all 0.3s;
}

.custom-reset-button:hover {
  background: #e4e7ed;
  color: #1a2f54;
}

.custom-refresh-button {
  background: #e7f3ff;
  border-color: #409eff;
  color: #409eff;
  transition: all 0.3s;
}

.custom-refresh-button:hover {
  background: #409eff;
  color: white;
}

/* 反馈列表样式 */
.feedback-list-card {
  position: relative;
}

.list-header {
  position: relative;
  padding: 16px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.list-header h3 {
  color: white;
  position: relative;
  z-index: 2;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.header-gradient {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 100%;
  background: linear-gradient(135deg, #4e6694 0%, #3b527a 100%);
  z-index: 1;
}

.total-feedbacks {
  position: relative;
  z-index: 2;
  color: white;
  font-size: 14px;
}

.total-feedbacks .highlight {
  font-weight: bold;
  color: #ffd04b;
}

.feedback-table {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.feedback-table .el-table__header) {
  background-color: #f0f5ff;
}

:deep(.feedback-table .el-table th) {
  background-color: #f0f5ff;
  color: #1a2f54;
  font-weight: 600;
}

/* 表格内容样式 */
.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.username {
  font-weight: 500;
  color: #1a2f54;
}

.title-cell {
  max-width: 200px;
}

.title-text {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.4;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.detail-button, .delete-button {
  padding: 5px 10px;
  border-radius: 4px;
  transition: all 0.2s;
}

.detail-button {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409eff;
}

.delete-button {
  background-color: rgba(245, 108, 108, 0.1);
  color: #f56c6c;
}

.detail-button:hover {
  background-color: rgba(64, 158, 255, 0.2);
}

.delete-button:hover {
  background-color: rgba(245, 108, 108, 0.2);
}

/* 分页样式 */
.pagination-container {
  padding: 20px;
  display: flex;
  justify-content: center;
}

/* 对话框样式 */
.feedback-detail-dialog .feedback-detail-card {
  padding: 20px;
  background: #f9fafc;
  border-radius: 8px;
}

.feedback-header {
  margin-bottom: 20px;
}

.feedback-user {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-details {
  flex: 1;
}

.user-name {
  font-size: 18px;
  font-weight: 600;
  color: #1a2f54;
  margin-bottom: 8px;
}

.feedback-meta {
  display: flex;
  gap: 8px;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.detail-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.detail-item.full-width {
  grid-column: 1 / -1;
  flex-direction: column;
  align-items: flex-start;
}

.detail-label {
  font-weight: 600;
  color: #606266;
  min-width: 80px;
  white-space: nowrap;
}

.detail-value {
  color: #1a2f54;
  flex: 1;
}

.content-box, .reply-box {
  width: 100%;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: white;
  white-space: pre-line;
  line-height: 1.6;
  margin-top: 5px;
  min-height: 60px;
}

.reply-box {
  background: #f0f5ff;
  border-color: #d0d9ff;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .search-actions {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-actions {
    width: 100%;
    justify-content: flex-start;
  }
  
  .detail-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style>